<template>
    <div class="app-container">
      <div class="filter-container">
        <el-button icon="el-icon-plus" type="primary" @click="addGoods" size="small">新增</el-button>
      </div>
      <article>
          <el-table border :data="dataList">
              <el-table-column label="商品信息" align="center" min-width="200px" >
                <template slot-scope="scope">
                  <div class="flex flex-item--center">
                    <el-popover
                      placement="top-start"
                      trigger="hover">
                      <img :src="scope.row.productImgCn" class="previewImage">
                      <img :src="scope.row.productImgCn" class="thumbnail"  slot="reference">
                    </el-popover>
                    <span class="block-right">{{scope.row.productNameCn}}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="当前排序" align="center" min-width="200px" >
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.sortNo" controls-position="right" :min="0" size="small" :precision="0"></el-input-number>
                  </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" min-width="200px">
                  <template slot-scope="scope">
                      <el-button plain type="primary" size="mini" @click="toDditProduct(scope.row)">保存排序</el-button>
                      <el-button plain type="danger" size="mini" @click="toDelete(scope.row)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <list-pagination :total="total" :page="page" :pageSize="pageSize" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></list-pagination>
      </article>
      <el-dialog
          title="添加商品至限时"
          :visible.sync="dialogVisible"
          width="800px"
          :before-close="handleClose">
          <div class="editGoodsGounp">
              <span style="float:left;display:inline-block;height:36px;line-height:36px">商品名称：</span>
              <div style="width:300px;height:36px;float:left"><el-input v-model="goodName" placeholder="请输入商品名称" size="medium"></el-input></div>
              <el-button style="margin-left:32px" type="primary" size="medium" icon="el-icon-search" @click="search">搜索</el-button>
            <el-table :data="list" ref="multipleTable" border @selection-change="handleSelectionChange" width= "100%" style="margin-top:16px">
              <el-table-column type="selection" :selectable="checkboxT" width="55">
              </el-table-column>
              <el-table-column label="商品名称（中/英）" align="center">
                <template slot-scope="scope">
                  <div class="flex flex-item--center">
                    <el-popover
                      placement="top-start"
                      trigger="hover">
                      <img :src="scope.row.coverCn" class="previewImage">
                      <img :src="scope.row.coverCn" class="thumbnail"  slot="reference" style="width:50px">
                    </el-popover>
                    <span class="block-right">{{scope.row.nameCn}}/{{scope.row.nameEn}}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品编码" prop="sn" align="center">
              </el-table-column>
            </el-table>
          <div style="width:100px;height:36px;float:left">
            <el-checkbox style="margin-top:16px" @change="toggleSelection(list)">全选</el-checkbox>
          </div>
          <div style="margin-top:16px;height:36px;float:right">
              <el-pagination
              @size-change="handleSizeChanges"
              @current-change="handleCurrentChanges"
              :current-page="currentPage4"
              :page-sizes="[5, 10, 20, 40]"
              :page-size="screenList.pageSize"
              layout="total, sizes, prev, pager, next"
              :total="totals">
            </el-pagination>
          </div>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button size="small" @click="dialogVisible = false">取 消</el-button>
              <el-button size="small" type="primary" @click="makeSure()">确 定</el-button>
          </span>
      </el-dialog>
    </div>
</template>
<script>
import list from '@/mixins/List'
import listPagination from '@/components/ListPagination'
import {
  productTimePricePage, deleteProductTimePrice, listProductSelect, addProductTimePrice, updateProductTimePricee
} from '@/api/specialOffer'
export default {
  name: 'screenAdList',
  mixins: [list],
  data () {
    return {
      dataList: [],
      imgList: [],
      list: [],
      multipleSelection: [],
      uploadFileUrl: `${process.env.BASE_API}/img/upload`,
      dialogVisible: false,
      dialogVisibles: false,
      productsOperate: {},
      totals: 0,
      currentPage4: 5,
      goodName: '',
      rowSort: '',
      operation: '',
      rowId: '',
      item: {},
      disabled: '',
      screenList: {
        pageNum: 1,
        pageSize: 5
      },
      addGoodsList: {},
      addGoodsId: [],
      adDialogTitles: {
        goodName: '商品名称：'
      },
      adDialogRules: {
        goodName: [{ required: true, message: '标题不能为空', trigger: 'change' }]
      }
    }
  },
  components: {
    listPagination
  },
  watch: {
    goodName: {
      handler () {
        if (this.goodName === '') {
          this.screenList.condition = this.goodName
          this.plugin()
        }
      },
      deep: true
    },
    multipleSelection: function () {
      let arr = []
      for (let i in this.multipleSelection) {
        arr.push(this.multipleSelection[i].id)
      }
      this.addGoodsId = arr
    }

  },
  created () {

  },
  mounted () {
    this.getList()
  },
  methods: {
    async getList () { // 列表
      let parentId = Number(this.$route.query.operateId)
      let { data } = await productTimePricePage({
        pageNum: this.page,
        pageSize: this.pageSize,
        parentId: parentId
      })
      this.dataList = data.list
      this.total = data.total
    },
    plugin () {
      this.screenList.operateId = Number(this.$route.query.operateId)
      listProductSelect(this.screenList).then(res => {
        this.list = res.data.list
        this.totals = res.data.total
        this.$nextTick(function () {
          this.list.forEach(i => {
            if (i.status === 1) {
              this.$refs.multipleTable.toggleRowSelection(i, true)
            }// 设置默认选中
          })
        })
        this.$refs.multipleTable.clearSelection()
      })
      delete this.addGoodsList.product
    },
    checkboxT (row, index) {
      if (row.status === 1) {
        return 0
      } else {
        return 1
      }
    },

    toDditProduct (row) {
      this.rowId = row.id
      this.rowSort = row.sortNo
      this.$confirm('此操作将该分类商品进行排序, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateProductTimePricee({
          'id': this.rowId,
          'sortNo': this.rowSort
        }).then(
          res => {
            if (res.code === 200) {
              this.dialogVisibles = false
              this.getList()
              this.$message.success('操作成功')
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    toDelete (row) {
      this.rowId = row.id
      this.$confirm('此操作将永久删除该分类商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProductTimePrice({
          'id': this.rowId
        }).then(res => {
          if (res.code === 200) {
            this.dialogVisibles = false
            this.getList()
            this.$message.success('删除成功')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addGoods () {
      this.goodName = ''
      this.plugin()
      this.dialogVisible = true
    },
    toggleSelection (rows) {
      // console.log(rows)
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    search () {
      if (this.goodName === '') {
        this.$message('搜索条件不能为空')
        return false
      }
      this.screenList.condition = this.goodName
      listProductSelect(this.screenList).then(res => {
        this.list = res.data.list
        this.totals = res.data.total
      })
    },
    makeSure () {
      if (this.addGoodsId.length === 0) {
        this.$message('请先勾选对应商品')
      }
      var str = ''
      for (let item of this.addGoodsId) {
        str += item + '|'
      }
      str = str.substr(0, str.length - 1)
      this.addGoodsList.groupId = Number(this.$route.query.operateId)
      this.addGoodsList.ids = String(str)
      console.log(this.addGoodsList)
      addProductTimePrice(this.addGoodsList).then(res => {
        if (res.code === 200) {
          this.dialogVisible = false
          this.$message.success('添加成功')
          this.getList()
        }
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    onBeforeUpload (file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isIMAGE && isLt2M
    },
    handleUploaderRemove (file, fileList, activeUploader, index) {

    },
    handleGoodsDetailUploadSuccess (response, file, fileList) {
      this.detailImages.push(response.data)
    },
    toAddAdvertisement () {
      this.fatheraddAdvertiseman = true
    },
    handleClose () {
      this.dialogVisible = false
    },
    handleSizeChanges (val) {
      this.screenList.pageSize = val
      this.plugin()
    },
    handleCurrentChanges (val) {
      this.screenList.pageNum = val
      this.plugin()
    }
  }
}
</script>
<style lang="scss" scoped>
    header{
        width: 100%;
        height: 72px;
        padding: 16px 0;
    }
    .editGoodsGounp {
      width: 100%;
      height: auto;
      padding: 20px 20px 40px;
      margin-bottom:8px;
    }
</style>
